#!/bin/bash

# Development server startup script

set -e

echo "🚀 Starting Crawl4AI Backend Development Server"
echo "=============================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_info() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# Check if virtual environment is activated
if [[ "$VIRTUAL_ENV" == "" ]]; then
    print_warning "Virtual environment not detected. Consider activating one."
fi

# Load environment variables
if [ -f .env ]; then
    print_status "Loading environment variables from .env"
    # Clear any old database/redis environment variables first
    unset DATABASE_URL DATABASE_POOL_SIZE DATABASE_MAX_OVERFLOW REDIS_URL REDIS_EXPIRE_TIME
    # Load new environment variables
    export $(cat .env | grep -v '^#' | xargs)
else
    print_warning ".env file not found. Using default values."
fi

# Set development defaults
export DEBUG=${DEBUG:-true}
export HOST=${HOST:-0.0.0.0}
export PORT=${PORT:-8001}
export LOG_LEVEL=${LOG_LEVEL:-DEBUG}

# Create necessary directories
mkdir -p logs
mkdir -p uploads

# Check dependencies
print_status "Checking dependencies..."
if ! python -c "import fastapi, uvicorn, pydantic" 2>/dev/null; then
    print_error "Missing required dependencies. Please run: pip install -r requirements.txt"
    exit 1
fi

# Storage setup
print_status "Setting up JSON storage..."
if [ "$DATA_DIR" == "" ]; then
    export DATA_DIR="data"
fi

# Create data directory
mkdir -p "$DATA_DIR"
print_status "JSON storage directory created: $DATA_DIR"

# Start the development server
print_status "Starting development server..."
print_info "Server will be available at: http://${HOST}:${PORT}"
print_info "API documentation: http://${HOST}:${PORT}/api/docs"
print_info "Press Ctrl+C to stop the server"

# Start with auto-reload enabled
uvicorn app.main:app \
    --host $HOST \
    --port $PORT \
    --reload \
    --reload-dir app \
    --log-level ${LOG_LEVEL} \
    --access-log
